package com.hyjiacan.h2c

import java.io.BufferedReader
import java.io.Closeable
import java.io.File
import java.io.InputStreamReader

class SqlResolver(file: File) : Iterator<String>, Closeable {
    private val buffer: StringBuilder = StringBuilder()
    private var fileReader: InputStreamReader = file.reader(Charsets.UTF_8)
    private val reader: BufferedReader = BufferedReader(fileReader)
    private val lineIterator: Iterator<String> = reader.lineSequence().iterator()

    override fun hasNext(): Boolean {
        return lineIterator.hasNext()
    }

    override fun next(): String {

        while (lineIterator.hasNext()) {
            val line = lineIterator.next()
            if (line.startsWith("--")) {
                continue
            }
            buffer.append(line)

            if (!line.endsWith(';')) {
                buffer.append("\n")
                continue
            }
            break
        }
        val sql = buffer.toString()
        buffer.clear()

        return sql
    }

    override fun close() {
        reader.close()
        fileReader.close()
    }
}